<?php

namespace App\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Support;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;

/**
 * \App\Models\User
 *
 * @property int $id
 * @property string $name 用户名
 * @property string $mobile 手机号
 * @property string $password 密码
 * @property string $avatar 头像
 * @property int $status 0刚注册不能登录 1 启用 2禁用
 * @property int $is_admin 是否超级管理员 1表示是超级管理员
 * @property string $last_login_ip 最后一次的登录ip
 * @property int $login_count 登录次数
 * @property Support\Carbon|null $created_at 创建时间
 * @property Support\Carbon|null $updated_at 更新时间
 * @property string|null $deleted_at 软删除时间
 */
class User extends Authenticatable implements JWTSubject
{
    use HasApiTokens, HasFactory, Notifiable, SoftDeletes;

    const DEFAULT_AVATAR = 'http://myalike.oss-cn-chengdu.aliyuncs.com/images/20220926/e1729a9e8361dc4b25abf06244f03043.jpeg';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $guarded = ['id'];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        "token",
        "expire",
        "pivot", //隐藏中间表数据
    ];

    /**
     * @param DateTimeInterface $date
     * @return string
     * 重写模型的serializeDate方法
     * "created_at": "2022-05-11T14:31:02.000000Z", 格式变为 "created_at": "2022-05-11 14:45:25",
     */
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 重写方法 JWTSubject, 获取token用
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey(); // TODO: Implement getJWTIdentifier() method.
    }

    /**
     * 重写方法 JWTSubject, 获取token用
     *
     * @return string[]
     */
    public function getJWTCustomClaims()
    {
        return [
//            'role' => 'user'
        ];  // TODO: Implement getJWTCustomClaims() method.
    }

    /**
     * 设置密码自动加密
     *
     * @param $value
     * @return string
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }

    /**
     * 一个用户拥有多个角色 N:N关联
     * @return BelongsToMany
     */
    public function roles(): BelongsToMany
    {
        $companyId = request()->input('company_id'); //这里不要后端取值，由前端传值

        return $this->belongsToMany(Role::class, 'company_user', 'user_id', 'role_id')
            ->when($companyId, function ($query) use ($companyId) {
                $query->where('roles.company_id', $companyId);
            })
            ->select(['roles.id', 'roles.company_id', 'roles.title', 'roles.status']);
    }

    /**
     * 一个用户所属公司多个公司
     * 超管登录后，在用户管理看到的是全部
     * 公司管理员在组织架构看到当前公司的信息，这时候会传过来 company_id
     * N:N 关联
     * @return BelongsToMany
     */
    public function companies(): BelongsToMany
    {
        $companyId = request()->input('company_id'); //这里不要后端取值，由前端传值

        return $this->belongsToMany(Company::class, 'company_user')
            ->when($companyId, function ($query) use ($companyId) {
                $query->where('companies.id', $companyId);
            })
            ->distinct()
            ->where('companies.status', 1)
            ->where('company_user.status', 1)
            //->where('company_user.role_id', '>' , 1)
            ->withPivot('is_admin')
            ->select(['companies.id', 'companies.title']);
    }

    /**
     * 一个用户可以属于多个部门
     * N:N 关联
     * @return BelongsToMany
     */
    public function departments(): BelongsToMany
    {
        return $this->belongsToMany(Department::class, 'department_user')
            ->select(['departments.id', 'departments.title']);
    }

    /**
     * 一个用户属于多个项目
     * N:N 关联
     * @return BelongsToMany
     */
    public function projects(): BelongsToMany
    {
        $companyId = request()->input('company_id'); //这里不要后端取值，由前端传值

        return $this->belongsToMany(Project::class, 'project_user')
            ->when($companyId, function ($query) use ($companyId) {
                $query->where('projects.company_id', $companyId);
            })
            ->select(['projects.id', 'projects.title']); //获取中间表字段;
    }

    /**
     * 一个用户属于多个单位
     * N:N 关联
     * @return BelongsToMany
     */
    public function partCompanies(): BelongsToMany
    {
        $companyId = request()->input('company_id'); //这里不要后端取值，由前端传值

        return $this->belongsToMany(PartCompany::class, 'part_company_user')
            ->when($companyId, function ($query) use ($companyId) {
                $query->where('part_companies.company_id', $companyId);
            })
            ->select(['part_companies.id', 'part_companies.title']);

    }

}
